package wang.lxl;

import java.io.InputStream;
import java.util.Objects;

public class TestClassLoader {
    public static void main(String[] args) throws Exception {
        ClassLoader myloader = new ClassLoader() {
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring((name.lastIndexOf(".") + 1)) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if (Objects.isNull(is)) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (Exception e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };

        Object obj = myloader.loadClass("wang.lxl.TestClassLoader").newInstance();
        System.out.println(obj.getClass());
        // wang.lxl.TestClassLoader$1@4dc63996
        System.out.println(obj.getClass().getClassLoader());
        TestClassLoader testClassLoader = new TestClassLoader();
        // sun.misc.Launcher$AppClassLoader@18b4aac2
        System.out.println(testClassLoader.getClass().getClassLoader());
        System.out.println(obj instanceof wang.lxl.TestClassLoader);

    }
}
